<?php

/***************************************************************\
* FILE:		sys/pages/groupy.inc
* SECTION:	pages > playing group management
* FUNCTION:	
* USES:	
* INCLUDES:		
* PRODUCES:	
* LAUNCHES:	
\***************************************************************/

include_once('sys/gamefunctions.inc');
include_once('sys/regionfunctions.inc');

/**
 * adds extra access checks, dependent on page state
 */
function page_inc_check_access() {
	check_access("READ");
}

function page_inc_execute_action($action) {
	global $PAGE, $CONFIG;

	switch($action) {
		case "edit":
			if (!$PAGE['id'])
				errorpage(9);
			$sqlresult = db_do_query(db_query_select(array(array("*")), array("GROUPY"), "groupy_id = {$PAGE['id']}"));
			if (db_num_rows($sqlresult) != 1)
				errorpage(404);
			$groupy = db_fetch_array($sqlresult);
			if ($groupy['admin'] != $_SESSION['user_id'])
				errorpage(5);
		case "add":
			if (!$_SESSION['user_id'])
				errorpage(6);
				
			if ($_POST['submitted']) {
			
				$ok = 1;
				$ok = (check_exists($_POST['groupname'], "naam") and $ok) ? 1 : 0;
				$ok = (check_tags($_POST['groupname'], "naam") and $ok) ? 1 : 0;
				if (ereg("^parent[0-9]+$", $_POST['region'])) {
					$ok = (check_exists($_POST['region_name'], "naam regio") and $ok) ? 1 : 0;
					$ok = (check_tags($_POST['region_name'], "naam regio") and $ok) ? 1 : 0;
				}
				if (check_chars($_POST["admin"], "beheerder heeft een ongeldige gebruikersnaam")) {
					$sqlresult = db_do_query(db_query_select(array(array('user_id')), array('MEMBER'), "nick LIKE '{$_POST["admin"]}'"));
					$ok = (check_input(db_num_rows($sqlresult) == 1, "lid '{$_POST["admin"]}' is onbekend") and $ok) ? 1 : 0;
					$m = db_fetch_array($sqlresult);
					$adminid = $m['user_id'];
				}

				$ok = (check_exists($_POST['description'], "beschrijving") and $ok) ? 1 : 0;
				$ok = (check_tags_advanced($_POST['description'], "beschrijving") and $ok) ? 1 : 0;
				$ok = (check_tags_tables($_POST['description'], "beschrijving") and $ok) ? 1 : 0;

				$ok = (check_exists($_POST['region'], "locatie") and $ok) ? 1 : 0;
				
				$registered = intval($_POST['registered_members']);
				$new = ($_POST['new_members'] != "NONE") ? intval($_POST['new_members']) : 0;
				$memberids = array();
				
				for ($i = 1; $i <= $registered; $i++) {
					$memberids[$i] = $_POST["member_$i"];
				}
				for ($i = $registered+1; $i <= $registered + $new; $i++) {
					if (check_chars($_POST["member_{$i}"], "lid #$i heeft een ongeldige gebruikersnaam")) {
						$sqlresult = db_do_query(db_query_select(array(array('user_id')), array('MEMBER'), "nick LIKE '{$_POST["member_{$i}"]}'"));
						$ok = (check_input(db_num_rows($sqlresult) == 1, "lid '{$_POST["member_{$i}"]}' is onbekend") and $ok) ? 1 : 0;
						$m = db_fetch_array($sqlresult);
						$memberids[$i] = $m['user_id'];
					}
				}
				
				$registered = intval($_POST['registered_games']);
				$new = ($_POST['new_games'] != "NONE") ? intval($_POST['new_games']) : 0;
				for ($i = 1; $i <= $registered; $i++) {
					$ok = (check_int($_POST["game_{$i}_freq"], "spel #$i") and $ok) ? 1 : 0;
					$ok = (check_input($_POST["game_{$i}_freq"] > 0, "spel #$i - frequentie niet ingevuld") and $ok) ? 1 : 0;
				}
				for ($i = $registered+1; $i <= $registered + $new; $i++) {
					$ok = (check_int($_POST["game_{$i}_freq"], "spel #$i") and $ok) ? 1 : 0;
					$ok = (check_input($_POST["game_{$i}_freq"] > 0, "spel #$i - frequentie niet ingevuld") and $ok) ? 1 : 0;
					if ($_POST["game_{$i}"] == "NEW") {
						$ok = (check_int($_POST["game_{$i}_type"], "spel #$i - soort") and $ok) ? 1 : 0;
						$ok = (check_input($_POST["game_{$i}_type"], "spel #$i - soort niet ingevuld") and $ok) ? 1 : 0;
						$ok = (check_exists($_POST["game_{$i}_name"], "spel #$i - naam") and $ok) ? 1 : 0;
						$ok = (check_tags($_POST["game_{$i}_name"], "spel #$i - naam") and $ok) ? 1 : 0;
					} else {
						$ok = (check_int($_POST["game_{$i}"], "spel #$i") and $ok) ? 1 : 0;
						$ok = (check_input($_POST["game_{$i}"] > 0, "spel #$i niet ingevuld") and $ok) ? 1 : 0;
					}
				}
				
				if ($ok) {
				
					if ($_GET['action'] == "add") { // add group
						db_do_query(db_query_insert(array('admin', 'description', 'groupname'), array($adminid, db_sqlize($_POST['description']), db_sqlize($_POST['groupname'])), "GROUPY"));
						$groupy_id = db_insert_id();
					} else { // update group
						db_do_query(db_query_update(array('admin', 'description', 'groupname'), array($adminid, db_sqlize($_POST['description']), db_sqlize($_POST['groupname'])), "GROUPY", "groupy_id = {$groupy['groupy_id']}"));
						$groupy_id = $groupy['groupy_id'];
					}
						
					if ($_POST['region'] != intval($groupy['region_id'])) {
						if (ereg("^parent[0-9]+$", $_POST['region'])) { // new region
							db_do_query(db_query_insert(array('name'), array(db_sqlize($_POST['region_name'])), "REGION"));
							$region_id = db_insert_id();
							db_do_query(db_query_insert(array('parent_region', 'sub_region'), array(substr($_POST['region'], 6), $region_id), "REGION_TREE"));
						} else {
							$region_id = $_POST['region'];
						}
						db_do_query(db_query_update(array('region_id'), array($region_id), "GROUPY", "groupy_id = {$groupy_id}"));
					}
					
					// members
					$registered = intval($_POST['registered_members']);
					$new = ($_POST['new_members'] != "NONE") ? intval($_POST['new_members']) : 0;
					for ($i = 1; $i <= $registered; $i++)
						if ($_POST["member_{$i}_kick"]) {
							db_do_query(db_query_delete("IN_GROUP", "user_id = {$memberids[$i]} AND groupy_id = {$groupy_id}"));
						add_alert("{$_SESSION['member']['nick']} heeft je uit spelersgroep <a href=/service/{$groupy_id}.groupy>{$_POST['groupname']}</a> verwijderd", "", $memberids[$i]);
						}
					for ($i = $registered+1; $i <= $registered + $new; $i++) {
						db_do_query(db_query_insert(array('user_id', 'groupy_id'), array($memberids[$i], $groupy_id), "IN_GROUP"));
						add_alert("{$_SESSION['member']['nick']} heeft je aan spelersgroep <a href=/service/{$groupy_id}.groupy>{$_POST['groupname']}</a> toegevoegd", "", $memberids[$i]);
					}
					
					// games	
					$registered = intval($_POST['registered_games']);
					$new = ($_POST['new_games'] != "NONE") ? intval($_POST['new_games']) : 0;
					for ($i = 1; $i <= $registered; $i++) {
						if ($_POST["game_{$i}_del"])
							db_do_query(db_query_delete("GROUPY_PLAYS", "groupy_id = {$groupy_id} AND game_id = {$_POST["game_{$i}"]}"));
						else 
							db_do_query(db_query_update(array('play_status_id'), array($_POST["game_{$i}_freq"]), "GROUPY_PLAYS", "groupy_id = {$groupy_id} AND game_id = {$_POST["game_{$i}"]}"));
					}
					for ($i = $registered+1; $i <= $registered + $new; $i++) {
						if ($_POST["game_{$i}"] == "NEW") {
							db_do_query(db_query_insert(array('name'), array(db_sqlize($_POST["game_{$i}_name"])), "GAME"));
							$game_id = db_insert_id();
							db_do_query(db_query_insert(array('game_id', 'game_type_id'), array($game_id, $_POST["game_{$i}_type"]), "GAME_OF_TYPE"));
						} else
							$game_id = $_POST["game_{$i}"];
						db_do_query(db_query_insert(array('groupy_id', 'game_id', 'play_status_id'), array($groupy_id, $game_id, $_POST["game_{$i}_freq"]), "GROUPY_PLAYS"));
					}
					
					endpage("OK, de gegevens zijn verwerkt!<script language=JavaScript>setTimeout(\"location.href='/service/{$groupy_id}.groupy'\", 1500);</script>");
				}
			}
			
			$inputs = array();
			
			$inputs[] = form_header("Groepsgegevens");
			$inputs[] = form_input_field("Naam", "groupname", $groupy['groupname']);
			$inputs[] = form_input_field("Beheerder", "admin", $_SESSION['member']['nick']);
			
			if (($_POST['region'] == "NEW")) {
				$kv = region_get_regions_kv(1);
				$inputs[] = form_input_field("Regio", "region_name");
				$inputs[] = form_input_select("Locatie", "region", $kv['keys'], $kv['values'], "kies een regio", $profile['region_id']);
			} else {
				$kv = region_get_regions_kv();
				$inputs[] = form_input_select("Regio", "region", array_merge(array("NEW"), $kv['keys']), array_merge(array("NIEUWE REGIO"), $kv['values']), "kies een regio", $groupy['region_id'], "document.groupform.submit()");
			}
			
			$inputs[] = form_input_text("Beschrijving", "description", $groupy['description']);

			$inputs[] = form_header("Leden");
			
			$members = db_do_query(db_query_select(array(array(), "MEMBER.nick, MEMBER.user_id"), array("MEMBER INNER JOIN IN_GROUP ON MEMBER.user_id = IN_GROUP.user_id", "DUMMY"), "groupy_id = " . intval($groupy['groupy_id'])));
			$n = 0;
			if (db_num_rows($members) > 0) {
				while ($m = db_fetch_array($members)) {
					$n++;
					$inputs[] = form_input_hidden("member_{$n}", $m['user_id']);
					$inputs[] = form_input_checkbox("Verwijder {$m['nick']} uit de groep", "member_{$n}_kick");
				}
			}
			$inputs[] = form_input_hidden("registered_members", $n);
			$inputs[] = form_input_select("Leden toevoegen", "new_members", array("NONE", 1, 2, 3, 4, 5, 6, 7, 8), array("geen", "1 lid", "2 leden", "3 leden", "4 leden", "5 leden", "6 leden", "7 leden", "8 leden"), "", "", "document.groupform.submit()");
			
			if ($_POST['new_members']) {
				$max = $_POST['new_members'] + $n;
				for ($n = $n+1; $n <= $max; $n++) {
					$inputs[] = form_input_field("Lid #$n", "member_{$n}");
				}
			}			

			$inputs[] = form_header("Spellen");
		
			$play_status = get_keys_and_values("play_status_id", "play_status", "PLAY_STATUS");
			$game_tree = game_get_games();
			$game_types = get_keys_and_values("game_type_id", "game_type", "GAME_TYPE");
			$game_kv = game_get_games_kv();
			
			$games = db_do_query(db_query_select(array(array("game_id, play_status_id")), array("GROUPY_PLAYS"), "groupy_id = " . intval($groupy['groupy_id'])));
			
			$n = 0;
			if (db_num_rows($games) > 0) {
				while ($g = db_fetch_array($games)) {
					$n++;
					$inputs[] = form_input_hidden("game_{$n}", $g['game_id']);
					$inputs[] = form_input_select("Spel #{$n}", "game_{$n}_dummy", $game_kv['keys'], $game_kv['values'], "", $g['game_id'], "", 1, 1);
					$inputs[] = form_input_select("", "game_{$n}_freq", $play_status['keys'], $play_status['values'], "", $g['play_status_id']);
					$inputs[] = form_input_checkbox("Verwijder dit spel", "game_{$n}_del");
				}	
			}
			$inputs[] = form_input_hidden("registered_games", $n);
			$inputs[] = form_input_select("Spellen toevoegen", "new_games", array("NONE", 1, 2, 3, 4, 5), array("geen", "1 spel", "2 spellen", "3 spellen", "4 spellen", "5 spellen"), "", "", "document.groupform.submit()");
			
			if ($_POST['new_games'] != "NONE") {
				$max = $n + $_POST['new_games'];
				array_unshift($game_kv['keys'], "NEW");
				array_unshift($game_kv['values'], "nieuw spel toevoegen");
				for ($n = $n+1; $n <= $max; $n++) {
					$inputs[] = form_input_select("Spel #{$n}", "game_{$n}", $game_kv['keys'], $game_kv['values'], "kies een spel", "", "document.groupform.submit()");
					if ($_POST["game_{$n}"] == "NEW") {
						$inputs[] = form_input_select("Spel #{$n} - soort", "game_{$n}_type", $game_types['keys'], $game_types['values']);
						$inputs[] = form_input_field("Spel #{$n} - naam", "game_{$n}_name");
					}
						
					$inputs[] = form_input_select("", "game_{$n}_freq", $play_status['keys'], $play_status['values']);
				}	
			}
			
			$PAGE['content']['form'] = form_create('groupform', array_reverse($inputs));

			break;
		default:
			add_alert("unknown action: $action");
			break;
	}
}

/**
 * execute page logic
 */
function page_inc_execute() {
	global $PAGE;
	
	if (!$_GET['action']) {
	
		$sqlresult = db_do_query(db_query_select(array(array(), "GROUPY.*, MEMBER.nick AS admin_nick"), array("GROUPY INNER JOIN MEMBER ON GROUPY.admin = MEMBER.user_id"), "groupy_id = {$PAGE['id']}"));
		if (db_num_rows($sqlresult) != 1)
			errorpage(404);
		$groupy = db_fetch_array($sqlresult);
		
		if ($groupy['admin'] == $_SESSION['user_id'])
			add_action("groupy-edit", "url-action", "edit");
		
		// fetch regional info
		if ($groupy['region_id']) {
			$region_tree = region_get_regions();
			$groupy['region'] = region_get_region_tree($groupy['region_id'], $region_tree);
		}
		
		// fetch member info
		$groupy['members'] = array();
		$sqlresult = db_do_query(db_query_select(array(array(), "MEMBER.nick, MEMBER.user_id"), array("IN_GROUP INNER JOIN MEMBER ON IN_GROUP.user_id = MEMBER.user_id", "DUMMY"), "groupy_id = {$PAGE['id']}", "nick ASC"));
		if (db_num_rows($sqlresult) > 0)
			while ($m = db_fetch_array($sqlresult))
				$groupy['members'][] = $m;
		
		// fetch gaming info
		$groupy['games'] = array();
		$sqlresult = db_do_query(db_query_select(array(array(), "PLAY_STATUS.*, GROUPY_PLAYS.game_id"), array("GROUPY_PLAYS INNER JOIN PLAY_STATUS ON GROUPY_PLAYS.play_status_id = PLAY_STATUS.play_status_id", "DUMMY"), "groupy_id = {$PAGE['id']}"));
		if (db_num_rows($sqlresult) > 0) {
			$game_tree = game_get_games();
			while ($g = db_fetch_array($sqlresult))
				$groupy['games'][] = array('game' => $game_tree[$g['game_id']], 'play_status' => $g['play_status']);
		}
		
		$PAGE['content']['groupy'] = $groupy;
	}
	
	$PAGE['content']['title'] = "Spelersgroep: " . (($_GET['action'] == "add") ? "toevoegen" : (($_GET['action'] == "edit") ? "aanpassen" : "'{$groupy['groupname']}'"));
}


/**
 * dress up page content using skin stuff
 */
function page_inc_dress() {
	global $PAGE;
	print_body($PAGE['content']['body']);
	if (($_GET['action'] == "edit") or ($_GET['action'] == "add"))
		print_form($PAGE['content']['form']);
	else
		print_groupy($PAGE['content']['groupy']);
}

?>
